// grid.js
Page({
  data: {
    imageUrl: '',
    rows: 3,
    cols: 3,
    formatIndex: 0,
    formats: ['JPEG', 'PNG', 'WebP'],
    quality: 90,
    
    // 图片原始尺寸
    originalWidth: 0,
    originalHeight: 0,
    
    // 预览画布
    previewCanvasWidth: 200,
    previewCanvasHeight: 200,
    
    // 网格线位置
    gridLines: {
      horizontal: [],
      vertical: []
    },
    
    // 切图结果
    splitImages: [],
    
    splitting: false
  },

  computed: {
    totalPieces() {
      return this.data.rows * this.data.cols;
    }
  },

  onLoad() {
    console.log('九宫格切图页面加载');
  },

  chooseImage() {
    wx.chooseMedia({
      count: 1,
      mediaType: ['image'],
      sourceType: ['album', 'camera'],
      success: (res) => {
        const tempFilePath = res.tempFiles[0].tempFilePath;
        this.setData({
          imageUrl: tempFilePath,
          splitImages: []
        });
        
        // 获取图片信息并更新预览
        this.initImageInfo(tempFilePath);
      },
      fail: (err) => {
        console.error('选择图片失败:', err);
        wx.showToast({
          title: '选择图片失败',
          icon: 'error'
        });
      }
    });
  },

  initImageInfo(imagePath) {
    wx.getImageInfo({
      src: imagePath,
      success: (res) => {
        const { width, height } = res;
        this.setData({
          originalWidth: width,
          originalHeight: height
        });
        
        this.updatePreview();
      },
      fail: (err) => {
        console.error('获取图片信息失败:', err);
        wx.showToast({
          title: '获取图片信息失败',
          icon: 'error'
        });
      }
    });
  },

  selectPreset(e) {
    const { rows, cols } = e.currentTarget.dataset;
    this.setData({
      rows: parseInt(rows),
      cols: parseInt(cols)
    });
    this.updatePreview();
  },

  onRowsChange(e) {
    this.setData({ rows: e.detail.value });
    this.updatePreview();
  },

  onColsChange(e) {
    this.setData({ cols: e.detail.value });
    this.updatePreview();
  },

  onFormatChange(e) {
    this.setData({
      formatIndex: e.detail.value
    });
  },

  onQualityChange(e) {
    this.setData({
      quality: e.detail.value
    });
  },

  updatePreview() {
    if (!this.data.imageUrl) return;
    
    const { originalWidth, originalHeight, rows, cols } = this.data;
    
    // 计算预览画布尺寸
    const maxPreviewSize = 200;
    const scale = Math.min(maxPreviewSize / originalWidth, maxPreviewSize / originalHeight);
    const previewWidth = originalWidth * scale;
    const previewHeight = originalHeight * scale;
    
    this.setData({
      previewCanvasWidth: previewWidth,
      previewCanvasHeight: previewHeight
    });
    
    // 直接使用旧版canvas以确保兼容性
    this.updatePreviewLegacy(previewWidth, previewHeight);
    
    // 计算网格线位置
    this.calculateGridLines(previewWidth, previewHeight);
  },

  // 降级到旧版canvas的预览方法
  updatePreviewLegacy(previewWidth, previewHeight) {
    const canvas = wx.createCanvasContext('gridPreviewCanvas', this);
    
    // 绘制图片预览
    canvas.drawImage(
      this.data.imageUrl,
      0, 0, previewWidth, previewHeight
    );
    
    canvas.draw();
  },

  calculateGridLines(width, height) {
    const { rows, cols } = this.data;
    const horizontal = [];
    const vertical = [];
    
    // 计算水平线位置
    for (let i = 1; i < rows; i++) {
      horizontal.push((height / rows) * i);
    }
    
    // 计算垂直线位置
    for (let i = 1; i < cols; i++) {
      vertical.push((width / cols) * i);
    }
    
    this.setData({
      gridLines: { horizontal, vertical },
      totalPieces: rows * cols
    });
  },

  splitImage() {
    if (!this.data.imageUrl) {
      wx.showToast({
        title: '请先选择图片',
        icon: 'error'
      });
      return;
    }

    this.setData({ splitting: true });

    const { originalWidth, originalHeight, rows, cols } = this.data;
    const pieceWidth = Math.floor(originalWidth / cols);
    const pieceHeight = Math.floor(originalHeight / rows);
    const splitImages = [];
    
    let processedCount = 0;
    const totalPieces = rows * cols;
    
    // 逐个生成切图
    for (let row = 0; row < rows; row++) {
      for (let col = 0; col < cols; col++) {
        const x = col * pieceWidth;
        const y = row * pieceHeight;
        
        this.createPiece(x, y, pieceWidth, pieceHeight, row, col, (imageData) => {
          splitImages.push(imageData);
          processedCount++;
          
          if (processedCount === totalPieces) {
            // 按行列顺序排序
            splitImages.sort((a, b) => {
              if (a.row !== b.row) return a.row - b.row;
              return a.col - b.col;
            });
            
            this.setData({
              splitImages,
              splitting: false
            });
            
            wx.showToast({
              title: `切图完成，共${totalPieces}张`,
              icon: 'success'
            });
          }
        });
      }
    }
  },

  createPiece(x, y, width, height, row, col, callback) {
    // 获取canvas节点
    // 直接使用旧版canvas以确保兼容性
      this.createPieceLegacy(x, y, width, height, row, col, callback);
  },

  // 降级到旧版canvas的切片方法
  createPieceLegacy(x, y, width, height, row, col, callback) {
    // 设置canvas尺寸
    this.setData({
      canvasWidth: width,
      canvasHeight: height
    });
    
    // 延时确保canvas尺寸更新
    setTimeout(() => {
      const canvas = wx.createCanvasContext('gridCanvas', this);
      
      // 绘制切片
      canvas.drawImage(
        this.data.imageUrl,
        x, y, width, height,
        0, 0, width, height
      );
      
      canvas.draw(false, () => {
      wx.canvasToTempFilePath({
        canvasId: 'gridCanvas',
        x: 0,
        y: 0,
        width: width,
        height: height,
        fileType: this.data.formats[this.data.formatIndex].toLowerCase(),
        quality: this.data.quality / 100,
        success: (res) => {
          const name = `piece_${row + 1}_${col + 1}.${this.data.formats[this.data.formatIndex].toLowerCase()}`;
          callback({
            url: res.tempFilePath,
            name: name,
            row: row,
            col: col
          });
        },
        fail: (err) => {
          console.error('生成切片失败:', err);
          wx.showToast({
            title: '生成切片失败',
            icon: 'error'
          });
        }
        }, this);
      });
     }, 50); // 延时50ms确保canvas尺寸更新
  },

  saveImage(e) {
    const index = e.currentTarget.dataset.index;
    const imageData = this.data.splitImages[index];
    
    if (!imageData) {
      wx.showToast({
        title: '图片不存在',
        icon: 'error'
      });
      return;
    }

    wx.saveImageToPhotosAlbum({
      filePath: imageData.url,
      success: () => {
        wx.showToast({
          title: `${imageData.name} 保存成功`,
          icon: 'success'
        });
      },
      fail: (err) => {
        if (err.errMsg.includes('auth deny')) {
          wx.showModal({
            title: '提示',
            content: '需要授权访问相册才能保存图片',
            success: (res) => {
              if (res.confirm) {
                wx.openSetting();
              }
            }
          });
        } else {
          wx.showToast({
            title: '保存失败',
            icon: 'error'
          });
        }
      }
    });
  },

  saveAllImages() {
    if (this.data.splitImages.length === 0) {
      wx.showToast({
        title: '没有可保存的图片',
        icon: 'error'
      });
      return;
    }

    wx.showModal({
      title: '批量保存',
      content: `确定要保存全部 ${this.data.splitImages.length} 张图片到相册吗？`,
      success: (res) => {
        if (res.confirm) {
          this.batchSaveImages();
        }
      }
    });
  },

  batchSaveImages() {
    const images = this.data.splitImages;
    let savedCount = 0;
    let failedCount = 0;
    
    wx.showLoading({
      title: `保存中 0/${images.length}`
    });
    
    images.forEach((imageData, index) => {
      wx.saveImageToPhotosAlbum({
        filePath: imageData.url,
        success: () => {
          savedCount++;
          wx.showLoading({
            title: `保存中 ${savedCount + failedCount}/${images.length}`
          });
          
          if (savedCount + failedCount === images.length) {
            wx.hideLoading();
            wx.showToast({
              title: `保存完成：成功${savedCount}张，失败${failedCount}张`,
              icon: savedCount > 0 ? 'success' : 'error',
              duration: 3000
            });
          }
        },
        fail: (err) => {
          failedCount++;
          console.error(`保存第${index + 1}张图片失败:`, err);
          
          if (savedCount + failedCount === images.length) {
            wx.hideLoading();
            wx.showToast({
              title: `保存完成：成功${savedCount}张，失败${failedCount}张`,
              icon: savedCount > 0 ? 'success' : 'error',
              duration: 3000
            });
          }
        }
      });
    });
  },

  saveGridImage() {
     if (!this.data.imageUrl) {
       wx.showToast({
         title: '请先选择图片',
         icon: 'error'
       });
       return;
     }
 
     wx.showLoading({
       title: '生成网格图中...'
     });
 
     // 直接使用旧版canvas以确保兼容性
     this.saveGridImageLegacy();
   },

   // 降级到旧版canvas的网格图保存方法
   saveGridImageLegacy() {
     const { originalWidth, originalHeight, rows, cols } = this.data;
     
     // 设置canvas尺寸
     this.setData({
       canvasWidth: originalWidth,
       canvasHeight: originalHeight
     });
     
     // 延时确保canvas尺寸更新
     setTimeout(() => {
       const canvas = wx.createCanvasContext('gridCanvas', this);
       
       // 绘制原图
       canvas.drawImage(this.data.imageUrl, 0, 0, originalWidth, originalHeight);
     
     // 绘制网格线
     canvas.setStrokeStyle('#ff0000');
     canvas.setLineWidth(2);
     
     // 绘制水平线
     for (let i = 1; i < rows; i++) {
       const y = (originalHeight / rows) * i;
       canvas.beginPath();
       canvas.moveTo(0, y);
       canvas.lineTo(originalWidth, y);
       canvas.stroke();
     }
     
     // 绘制垂直线
     for (let i = 1; i < cols; i++) {
       const x = (originalWidth / cols) * i;
       canvas.beginPath();
       canvas.moveTo(x, 0);
       canvas.lineTo(x, originalHeight);
       canvas.stroke();
     }
     
     canvas.draw(false, () => {
       // 导出图片
       wx.canvasToTempFilePath({
         canvasId: 'gridCanvas',
         fileType: this.data.formats[this.data.formatIndex].toLowerCase(),
         quality: this.data.quality / 100,
         success: (res) => {
           wx.hideLoading();
           wx.saveImageToPhotosAlbum({
             filePath: res.tempFilePath,
             success: () => {
               wx.showToast({
                 title: '网格图保存成功',
                 icon: 'success'
               });
             },
             fail: (err) => {
               if (err.errMsg.includes('auth deny')) {
                 wx.showModal({
                   title: '提示',
                   content: '需要授权访问相册才能保存图片',
                   success: (res) => {
                     if (res.confirm) {
                       wx.openSetting();
                     }
                   }
                 });
               } else {
                 wx.showToast({
                   title: '保存失败',
                   icon: 'error'
                 });
               }
             }
           });
         },
         fail: (err) => {
           wx.hideLoading();
           console.error('生成网格图失败:', err);
           wx.showToast({
             title: '生成网格图失败',
             icon: 'error'
           });
         }
       });
     });
     }, 50); // 延时50ms确保canvas尺寸更新
   },

  resetSettings() {
    this.setData({
      rows: 3,
      cols: 3,
      quality: 90,
      formatIndex: 0
    });
    this.updatePreview();
  }
})